//console.time( 'final.js' );

;(function() {

'use strict';

/**
 * @const
 */
var rSplitor = /[,;，； \n\r]+/;

/**
 * @type {function(string)}
 * @const
 */
var getConfig = Config.get;

/** @enum {Array.<string>}  */
var ButtonText = {
	NigthMode : !younight ? ['夜间模式', '切换至夜间模式'] : ['白天模式', '切换至白天模式'],
	signSwitch : !yousign ? ['关闭签名档', '隐藏所有用户的签名档'] : ['打开签名档', '显示所有用户的签名档']
};

/** @const */
var blacklistedPersons = decodeURI( getConfig('blacklistEditor') ).split( rSplitor );

// Reset vars and one off functions.
younight = getConfig( 'nightMode' ) ? younight : -1;
yousign = getConfig( 'signSwitch' ) ? yousign : -1;
if ( !getConfig( 'editorPlus' ) )
	EditorPlus.init = $.noop;
if ( !getConfig( 'JKscroll' ) )
	HotKey.init = $.noop;


//(We'd better know where it is before we take any action;)
/** @type {Object.<string, boolean>}  */
var TiebaWhere = {
	'' : true,
	i : pathhead === 'i',
	inside : !!$(".l_container").length,
	outside : !!$('#thread_list').length,
	club : pathhead === 'c'
};

/**
 * @type {Object.<string, function>}
 */
var FinalAction = {
	'' : function() {
		var inter = function() {
			'use strict';

			inter.errorTimes = inter.tryTimes || 0;
			var target = $( '.u_itieba' ),
				iTieba = $( '.s_itieba' );
			if ( ( target.length === 0 || iTieba.length === 0 ) &&  inter.errorTimes < 5 ) {
				inter.errorTimes++;
				setTimeout( inter, 150 );
				return;
			}

			var aims = decodeURI( getConfig( 'quickEntranceEditor' ) ).split( rSplitor );

			// Take a check in case that TieBa adds it back.
			if ( iTieba.hasClass( 'u_arrow' ) )
				return;
			iTieba.addClass( 'u_arrow' );
			var menu = $( '<div>' ).attr({
				'class' : 'u_ddl',
				'style' : 'display: none; top: -2px;'
			}).css( 'left', iTieba.prop( 'offsetLeft' ) - target.parent().prop( 'offsetLeft') + 'px' );
			target.mouseover( function() {
				if ( menu.children().length === 0 )
					_initMenu();
				target.children().eq( 0 ).css( 'visibility', 'hidden' );
				menu.show();
			});
			menu.mouseout( function() {
				menu.hide();
				target.children().eq( 0 ).css( 'visibility', 'visible' );
			});

			function _initMenu() {
				var menu_head = $( '<div>' ).addClass( 'u_ddl_tit' ).html( target.html() );
				menu.append( menu_head );

				var	menu_body2 = $( '<div>' ).addClass( 'u_ddl_con_top' );
				var _ul = $( '<ul>' ).appendTo( menu_body2 );
				aims.forEach( function( name ) {
					$( '<li>' )
							.append( $( '<a>' )
									.attr( 'href', '/f?ie=utf-8&kw=' + encodeURIComponent( name ) )
									.text( name )
							)
							.appendTo( _ul );
				});
				menu.append( $( '<div>' ).addClass( 'u_ddl_con' ).append( menu_body2 ) ).appendTo( target );
			}
		};

		if ( getConfig( 'quickEntrance' ) && getConfig( 'quickEntranceEditor' ) ) {
			setTimeout( inter, 150 );
		}
	},

	i : function() {
		$( document ).dblclick( badgeJump );
	},

	inside : function() {
		'use strict';
		// Insert switch-buttons in the nav-bar.
		insertNightModeButton();
		insertSignSwitchButton();

		$( document ).dblclick( badgeJump );

		setTimeout( EditorPlus.init, 0 );

		// Reset PostSuperClass's properties to make it fast.
		var postsHTML = $('.p_postlist').html();
		if ( !/#.+?#|百度密语/.test(postsHTML) || !getConfig('decodePost') )
			PostSuperClass.decode = $.self;
		if ( !/d_author_anonym/.test(postsHTML) || !getConfig('ipLookup') )
			PostSuperClass.addIpLink = $.self;
		if ( !getConfig('floorLink') )
			PostSuperClass.addFloorLink = $.self;
		if ( !getConfig('blacklist') )
			PostSuperClass.slash = $.self;


		// Loop for every floor.
		$( '.l_post' ).forEach( function( post ) {
			$.extend( post, PostSuperClass )
					.addFloorLink()
					.addIpLink()
					.decode()
					.slash();
		});

		HotKey.init();

	},

	outside : function( ajaxFlag ) {
		'use strict';

		addLastPageLink();
		slashOut( blacklistedPersons );
		insertNightModeButton();

		// Currently Tieba use an Ajax refresh method,
		// so I use a trick to monitor it.
		if ( $( '#list_area' ).length ) {
			var monitor = $( '<a>' ).attr( 'id', 'bdb-outer-monitor' );
			$( '#list_area' ).prepend( monitor );
		}

		ajaxFlag || setTimeout( EditorPlus.init, 0 );
	},

	club : function() {
		'use strict';
		if ( $( '#thread_table' ).length ) {
			addLastPageLink();
		} else if ( DEBUG ) { // For Miyu / UUcode debug only.
			$( "table.post" ).forEach( function( post ) {
				$.extend( post, PostSuperClass );
				post.decode( true );
			});
		}

		// Enable editor since TieBa doesn't kill it die. 2012-5-2
		$( '#add_post_form [disabled]' ).removeAttr( 'disabled' ).removeAttr( 'style' );
		$( '#unedit_layer_toolbar, #unedit_layer_content' ).remove();
	}
}; // ${ FinalAction } END

// OK, Let's begin:
switch ( true ) {

	case TiebaWhere.inside :
		FinalAction.inside();
		break;


	case TiebaWhere.outside :
		FinalAction.outside();
		// For Tieba's Ajax refresh.
		var onHashChange = function() {
			'use strict';
			if ( /!\/[mnv](?:\/p\d+)?/.test( location.hash ) ) {
				if ( $( '#bdb-outer-monitor' ).length || !$( '.thread_alt' ).length )
					setTimeout( onHashChange, 60 );
				else
					FinalAction.outside( true );
			}
		};
		window.addEventListener( 'hashchange', onHashChange, false );
		break;


	case TiebaWhere.i :
		FinalAction.i();
		break;


	case TiebaWhere.club :
		FinalAction.club();
		break;
}
FinalAction['']();


if ( location.search === '?kw=%D3%C6%D3%C6%C4%CE%BA%CE&ref=bdb-option-page' ) {
	invite( true );
} else if ( location.search.match( 'kw=%D3%C6%D3%C6%C4%CE%BA%CE' ) ) {
	invite( false );
}

// Functions.
/** @type {function(boolean=)} */
function invite( strongFlag ) {
	'use strict';
	if ( $( '#balv_dolike' ).length === 0 )
		return;
	var aim = $( '#balv_dolike' ),
		animate;
	var innerRadius = 1,
		outerRadius = 5,
		hue = 1,
		dir = 1;
	aim.mouseover( spark );
	if ( strongFlag )
		setInterval( spark, 2000 );

	function spark() {
		'use strict';
		if ( animate )
			return;
		animate = function() {
			var _aim = aim[0];
			var mask = _aim.style.webkitMask;
			var filter = _aim.style.webkitFilter;
			_aim.style.webkitMask = '-webkit-gradient(radial,39 17,'+innerRadius+',39 17,'+outerRadius+',from(#fff),color-stop(0.5,rgba(0,0,0,0.1)), to(#fff))';
			_aim.style.webkitFilter = 'hue-rotate(' + hue + 'deg)';
			innerRadius += 2.2; outerRadius += 3; hue += dir * (120-hue) / 10 + dir;
			if ( hue > 120 )
				dir = -1;
			else if ( hue < 11 )
				hue = 11;
			if ( animate )
				requestAnimationFrame( animate );
			else {
				_aim.style.webkitMask = '';
				_aim.style.webkitFilter = '';
			}
		};
		requestAnimationFrame( animate );
		setTimeout( function() {
			animate = null;
			innerRadius = 1, outerRadius = 5, hue = 1, dir = 1;
		}, 960 );
	}
}
/**
 * @param {Array.<string>} persons
 * @return {boolean|undefined}
 */
function slashOut( persons ) {
	'use strict';
	if ( !getConfig( 'blacklist' ) || !persons || !persons.length )
		return;
	if ( $( '#list_area' ).length && $( '.slashed', $( '#list_area' ) ).length )
		return false;

	for ( var p, links, i = persons.length; i--; ) {
		links = $( '//a[text()="' + persons[i] + '"]' );
		if ( links.length )
			links.forEach( slashOut_inner );
	}
	return true;
}
/**
 * @param {!HTMLElement} a
 */
function slashOut_inner( a ) {
	$( a ).addClass( 'slashed' );
}
function insertSignSwitchButton() {
	'use strict';

	if ( yousign === -1 || $( '#yousignSwitch' ).length )
		return;
	if ( TiebaWhere.inside ) {
		if ( $( '.j_quick_post' ).length === 0 )
			return;

		// add the interval
		$( '.j_quick_post' ).append( $( '.j_quick_post' ).childNodes()[2].cloneNode() );

		// add the button
		$( '<a>' ).attr({
					id : 'yousignSwitch',
					href : '',
					title : ButtonText.signSwitch[1]
				})
				.text( ButtonText.signSwitch[0] )
				.appendTo( $('.j_quick_post') )
				.click( switchesStorage.getSwitchFunc( 'signSwitch' ) );

	}
}
function insertNightModeButton() {
	'use strict';

	if ( younight === -1 || $( '#youNigthMode' ).length )
		return false;

	if ( TiebaWhere.outside && $( '#frs_good_nav' ).length ) {
		var a = $( '<span>' ).attr( 'id', 'youNigthMode' ).attr( 'style', 'float:right' );
		a.html( '<a href>' + ButtonText.NigthMode[1] + '</a>' ).click( switchesStorage.getSwitchFunc( 'nightMode' ) );
		$( '#frs_good_nav' ).append(a);
	} else if ( TiebaWhere.inside ) {
		if ( $( '.j_quick_post' ).length === 0 )
			return;
		var a = $( '<a>' ).attr({
			id : 'youNigthMode',
			href : '',
			title : ButtonText.NigthMode[1]
		}).text( ButtonText.NigthMode[0] ).click( switchesStorage.getSwitchFunc( 'nightMode' ) );

		var gap = $( '.j_quick_post' ).childNodes()[2].cloneNode();
		$( '.j_quick_post' ).append( gap, a );
	}

}
function badgeJump() {
	'use strict';
	var e = window.event, a = $( e.target );
	if ( a.attr( 'class' ).match( 'badge' ) && a.attr( 'title' ) ) {
		var badge_title = a.attr( 'title' ).split(' ')[0],
			bar_location = 'http://tieba.baidu.com/f?ie=utf-8&kw=' + encodeURI( badge_title );
		window.open( bar_location );
	}
}
function addLastPageLink() {
	"use strict";

	if ( !getConfig( 'lastPageLink' ) )
		return;
	if ( $( '.lastPage_a' ).length )
		return false;

	$( '.thread_title' ).forEach( function( td ) {
		td = $( td );
		var reply = td.parent().attr( 'replay' ) || td.parent().find( 'td' ).html();
		if ( +reply > 29 ) {
			var olink = td.find( 'a' ).attr( 'href' );
			$( '<a>' ).attr({
				'class' : 'lastPage_a',
				'href' : olink + '?pn=' + ( Math.ceil( ++reply / 30 ) ),
				'target' : '_blank'
			}).text( '-->>' ).appendTo( td );
		}
	});
	return true;
}

})();

//console.timeEnd( 'final.js' );